package org.artifact.core.plugin.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.artifact.core.context.bytebuf.IByteBuff;
import org.artifact.core.context.bytebuf.NetworkByteBuff;
import org.artifact.core.context.packet.NetworkPacket;
import org.artifact.core.server.ServerContext;

public class NetworkEncoder extends MessageToByteEncoder<NetworkPacket> {

	@Override
	protected void encode(ChannelHandlerContext ctx, NetworkPacket packet, ByteBuf out) throws Exception {
		// 1.标记写位置
		out.markWriterIndex();
		
		// 2.站位写入长度 
		out.writeInt(0);

		// 3.代理Bytebuf
//		IByteBuff byteBuff = new NetworkByteBuff(out);
		IByteBuff byteBuff = ServerContext.me().getProtocolBufferProvider().create(out);
		
		// 4.写入包内容
		packet.toByteBuff(byteBuff);

		// 5.取得包长
		int length = out.readableBytes();
		
		// 6.记录最后的写位置
		int lastWriterIndex  = byteBuff.getWriterIndex();
		
		// 7.还原到包长位置
		out.resetWriterIndex();
		
		// 8.写入包长
		out.writeInt(length - 4);
		
		// 9.还原真实写位置
		byteBuff.setWriterIndex(lastWriterIndex);
	}

}
